import json
import re

from django.contrib.auth.hashers import make_password
from django.core.mail import send_mail
from PIL import Image
from captcha.models import CaptchaStore

from django.contrib.auth import login, logout, authenticate

from django import http

from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger, InvalidPage
from django.http import HttpResponse
from django.urls import reverse
from django.views import View
from django.shortcuts import render, redirect
from django.views.generic import ListView

from boxuegu import settings
from courses.models import Course
from operation.models import UserCourse, UserFavorite, UserMessage
from organization.models import CourseOrg, Teacher
from users.models import Banner, Useremail, UserProfile
from users.utils import generic_verify_email_url, check_veryfy_email_token
from .forms import RegisterForm, ForgetForm, LoginForm


# 展示首页
class IndexView(View):
    def get(self, request):
        banners = Banner.objects.all()
        all_banners = []
        for banner in banners:
            all_banners.append({
                'id': banner.id,
                'image': banner.image
            })
        coursesall = Course.objects.all()
        courses = []
        for course in coursesall:
            courses.append({
                'id': course.id,
                'image': course.image,
                'degree': course.degree,
                'students': course.students,
                'name': course.name,
                'fav_nums': course.fav_nums
            })
        b_courses = Course.objects.all()
        banner_courses = []
        for b in b_courses:
            banner_courses.append({
                'id': b.id,
                'image': b.image
            })
        course_o = CourseOrg.objects.all()
        course_orgs = []
        for o in course_o:
            course_orgs.append({
                'id': o.id,
                'image': o.image,
                'tag': o.tag,
                'name': o.name
            })
        MEDIA_URL = settings.MEDIA_URL
        return render(request, 'index.html', {
            'all_banners': all_banners,
            'courses': courses,
            'banner_courses': banner_courses,
            'course_orgs': course_orgs,
            'MEDIA_URL': MEDIA_URL
        })


# 注册页面
class RegisterView(View):
    def get(self, request):
        # 生成表单对象
        register_form = RegisterForm()

        return render(request, 'register.html', {'register_form': register_form})

    def post(self, request):
        data = request.POST
        # 生成表单对象
        new_form = RegisterForm()
        # # 4.验证用户名
        register_form = RegisterForm(data)
        # # 验证表单
        if register_form.is_valid():
            email = register_form.cleaned_data.get('email')
            password = register_form.cleaned_data.get('password')
            try:
                useremail = UserProfile.objects.get(email=email)
                return render(request, 'register.html', {'emailerror': '邮箱已存在', 'register_form': new_form})
            except UserProfile.DoesNotExist:
                user = UserProfile.objects.create_user(email=email, password=password, username=email)
                return redirect(reverse('users:index'))
        else:
            return render(request, 'register.html', {'register_form': register_form})


# 登录页面
class LoginView(View):
    def get(self, request):
        return render(request, 'login.html')

    def post(self, request):
        data = request.POST
        new_login_form = LoginForm()
        login_form = LoginForm(data)
        if login_form.is_valid():
            username = login_form.cleaned_data.get('username')
            password = login_form.cleaned_data.get('password')

            user = authenticate(username=username, password=password)
            if user is None:
                return render(request, 'login.html', {'form_errors': new_login_form.errors})
            login(request, user)
            # # 设置状态保持周期
            response = redirect(reverse('users:index'))
            response.set_cookie('username', user.username, max_age=14 * 24 * 3600)
            return response
        else:
            return http.HttpResponseBadRequest('用户名密码错误')


# 退出登录
class LogoutView(View):
    def get(self, request):
        logout(request)
        # 重定向
        response = redirect(reverse('users:index'))
        # 删除session信息
        response.delete_cookie('username')

        return response


# 忘记密码
class ForgetPwdView(View):
    def get(self, request):
        forget_form = ForgetForm()
        return render(request, 'forgetpwd.html', {'forget_form': forget_form})

    def post(self, request):
        forget_form = ForgetForm()
        data = request.POST
        email = data.get('email')
        captcha = data.get('captcha_1')
        if not all([email, captcha]):
            return http.HttpResponseBadRequest('参数不全')
        try:
            count = UserProfile.objects.filter(email=email).count()
            captcha = CaptchaStore.objects.filter(challenge=captcha).count()
            if count == 0:
                return http.HttpResponseBadRequest('邮箱不存在')
            if captcha == 0:
                return http.HttpResponseBadRequest('验证码不正确')
            subject = '英雄联盟亚索五杀'
            message = 'Ｅ＋Ｑ＋Ａ＋Ａ＋Ｑ＋Ｅ＋Ｑ＋Ａ＋Ｒ＋Ｑ＋亮牌子'
            from_email = '博学谷项目<qi_rui_hua@163.com>'
            recipient_list = [email]
            verify_url = generic_verify_email_url(email)
            html_message = '<p>尊敬的用户您好！</p>' \
                           '<p>感谢您使用博学谷。</p>' \
                           '<p>您的邮箱为：%s 。请点击此链接激活您的邮箱：</p>' \
                           '<p><a href="%s">%s<a></p>' % (email, verify_url, verify_url)

            send_mail(
                subject=subject,
                message=message,
                from_email=from_email,
                recipient_list=recipient_list,
                html_message=html_message
            )
            return render(request, 'send_success.html')
        except Exception as e:
            return render(request, 'forgetpwd.html', {'forget_form': forget_form})


# 跳转到修改密码
class ResetView(View):
    def get(self, request, active_code):
        email = check_veryfy_email_token(active_code).get('email')
        count = UserProfile.objects.filter(email=email).count()
        if count == 0:
            return render(request, 'active_fail.html')

        return render(request, 'password_reset.html', {'email': email})


# 修改密码
class Modifypwd(View):
    def get(self, request):
        return render(request, 'password_reset.html')

    def post(self, request):
        data = request.POST
        email = data.get('email')
        if email is None:
            return redirect(reverse('users:login'))
        password1 = data.get('password1')
        password2 = data.get('password2')
        if not all([password1, password2]):
            return http.HttpResponseBadRequest('参数不全')
        if password1 != password2:
            return http.HttpResponseBadRequest('两次密码不一致')

        try:
            password = make_password(password1)
            UserProfile.objects.filter(email=email).update(password=password)
            return redirect(reverse('users:login'))
        except Exception as e:
            return redirect(reverse('users:modify_pwd'))


# 修改图片
class UploadImageView(View):
    def post(self, request):
        data = request.FILES
        image = data['image']
        MEDIA_URL = settings.MEDIA_URL
        img = Image.open(image)
        two_image = ('image/' + str(image))
        new_image = str(image)
        try:
            img.save(
                r'/home/python/Desktop/boxuegu/BoXueGu_shixun/boxuegu-data/boxuegu/static/media/image/' + new_image)  # 路径(绝对/相对)
            print('保存了图片')
        except:
            pass
        user_id = request.user.id

        try:
            user = UserProfile.objects.filter(id=user_id).update(
                image=two_image
            )
        except Exception as e:
            return e
        return http.JsonResponse({
            "status": "success",
            "msg": '头像修改成功'
        })


# 个人中心
class UserInfoView(View):
    def get(self, request):
        MEDIA_URL = settings.MEDIA_URL
        user_id = request.user.id
        if user_id is None:
            return redirect(reverse('users:login'))
        return render(request, 'usercenter-info.html', {'MEDIA_URL': MEDIA_URL})

    def post(self, request):
        data = request.POST
        nick_name = data.get('nick_name')
        birthday = data.get('birthday')
        gender = data.get('gender')
        address = data.get('address')
        mobile = data.get('mobile')
        email = data.get('email')
        user_id = request.user.id
        if not all([nick_name, birthday, gender, address, mobile, email]):
            return http.HttpResponseBadRequest('参数不全')

        try:
            user = UserProfile.objects.filter(id=user_id).update(
                nick_name=nick_name,
                birthday=birthday,
                gender=gender,
                address=address,
                mobile=mobile,
                email=email
            )
        except Exception as e:
            return http.JsonResponse({'status': 'error'})
        return http.JsonResponse({'status': 'success'})


# 用户中心－－－－我的消息
class MyMessageView(View):
    def get(self, request):
        # 指定 paginate_by 属性后开启分页功能，其值代表每一页包含多少篇文章
        user = request.user.id
        if user is None:
            user_id = 0
        else:
            user_id = user
        usermessages = UserMessage.objects.filter(user=user_id).filter(has_read=0)
        page = request.GET.get('page')
        paginator = Paginator(usermessages, 2)
        num_pages = paginator.num_pages
        try:
            messages = paginator.page(page)

        except PageNotAnInteger:
            # 如果请求的页数不是整数, 返回第一页。
            messages = paginator.page(1)
        except InvalidPage:
            # 如果请求的页数不存在, 重定向页面
            return HttpResponse('找不到页面的内容')
        except EmptyPage:
            # 如果请求的页数不在合法的页数范围内，返回结果的最后一页。
            messages = paginator.page(paginator.num_pages)

        MEDIA_URL = settings.MEDIA_URL
        return render(request, 'usercenter-message.html', {
            'messages': messages,
            'MEDIA_URL': MEDIA_URL,
            'num_pages': num_pages
        })


# 用户中心---我的收藏---消息分页
class MyMessagePageView(View):
    def get(self, request, page_id):
        if page_id is None:
            page = 1
        else:
            page = page_id
        user_id = request.user.id
        usermessages = UserMessage.objects.filter(user=user_id).filter(has_read=0)
        paginator = Paginator(usermessages, 2)
        num_pages = paginator.num_pages
        try:
            messages = paginator.page(page)

        except PageNotAnInteger:
            # 如果请求的页数不是整数, 返回第一页。
            messages = paginator.page(1)
        except InvalidPage:
            # 如果请求的页数不存在, 重定向页面
            return HttpResponse('找不到页面的内容')
        except EmptyPage:
            # 如果请求的页数不在合法的页数范围内，返回结果的最后一页。
            messages = paginator.page(paginator.num_pages)

        MEDIA_URL = settings.MEDIA_URL
        return render(request, 'usercenter-message.html', {
            'messages': messages,
            'MEDIA_URL': MEDIA_URL,
            'num_pages': num_pages
        })


# 用户中心------我的课程
class MyCourseView(View):
    def get(self, request):
        user_id = request.user.id
        courses = UserCourse.objects.all()
        MEDIA_URL = settings.MEDIA_URL
        try:
            user = UserCourse.objects.filter(user_id=user_id)
            new_list = []
            for new_value in user:
                new_list.append({
                    'course_id': new_value.course_id
                })
            user_courses = []
            for two_value in new_list:
                a = two_value.get('course_id')
                coures = Course.objects.get(id=a)
                user_courses.append({
                    'id': coures.id,
                    'image': coures.image,
                    'name': coures.name,
                    'learn_times': coures.learn_times,
                    'students': coures.students,
                    'fav_nums': coures.fav_nums
                })
        except Exception as e:
            return e
        return render(request, 'usercenter-mycourse.html', {
            'user_courses': user_courses,
            'MEDIA_URL': MEDIA_URL
        })


# 用户中心-----我的收藏---我的课程学校
class MyFavOrgView(View):
    def get(self, request):
        user_id = request.user.id
        # Entity.objects.filter(name_contains='kris').filter(address='beijing')
        try:
            list = UserFavorite.objects.filter(user_id=user_id).filter(fav_type=2)
            user = UserCourse.objects.filter(id=user_id)
            new_list = []
            for new_value, key in zip(user, list):
                new_list.append({
                    'course_id': new_value.course_id,
                    'id': key.fav_id
                })
            org_list = []
            for two_value in new_list:
                a = two_value.get('course_id')
                coures = Course.objects.get(id=a)
                courseorg = CourseOrg.objects.get(id=coures.course_org_id)

                org_list.append({
                    'id': two_value.get('id'),
                    'name': courseorg.name,
                    'address': courseorg.address,
                    'image': courseorg.image
                })
        except Exception as e:
            return e
        MEDIA_URL = settings.MEDIA_URL
        return render(request, 'usercenter-fav-org.html', {
            'org_list': org_list,
            'MEDIA_URL': MEDIA_URL
        })


# 用户中心---我的收藏----授课老师
class Myfavteacher(View):
    def get(self, request):
        user_id = request.user.id
        try:
            list = UserFavorite.objects.filter(user_id=user_id).filter(fav_type=2)
            user = UserCourse.objects.filter(user_id=user_id)
            new_list = []
            for new_value, key in zip(user, list):
                new_list.append({
                    'course_id': new_value.course_id,
                    'id': key.fav_id
                })
            teacher_list = []
            for two_value in new_list:
                a = two_value.get('course_id')
                coures = Course.objects.get(id=a)
                teacher = Teacher.objects.get(id=coures.teacher_id)
                count = Course.objects.filter(teacher_id=teacher.id).count()

                teacher_list.append({
                    'id': two_value.get('id'),
                    'name': teacher.name,
                    'work_years': teacher.work_years,
                    'get_course_nums': count,
                    'work_company': teacher.work_company,
                    'work_position': teacher.work_position,
                    'image': teacher.image
                })
        except Exception as e:
            return e

        MEDIA_URL = settings.MEDIA_URL
        return render(request, 'usercenter-fav-teacher.html', {
            'teacher_list': teacher_list,
            'MEDIA_URL': MEDIA_URL
        })


# 用户中心----我的收藏--公开课程
class Myfavcourse(View):
    def get(self, request):
        user_id = request.user.id
        MEDIA_URL = settings.MEDIA_URL
        try:
            userf = UserFavorite.objects.filter(user_id=user_id).filter(fav_type=1)
            user = UserCourse.objects.filter(user_id=user_id)
            new_list = []
            for new_value, key in zip(user, userf):
                new_list.append({
                    'course_id': new_value.course_id,
                    'id': key.fav_id
                })
            course_list = []
            for two_value in new_list:
                a = two_value.get('course_id')
                coures = Course.objects.get(id=a)
                course_list.append({
                    'id': two_value.get('id'),
                    'image': coures.image,
                    'learn_times': coures.learn_times,
                    'students': coures.students,
                    'name': coures.name
                })
        except Exception as e:
            return e
        return render(request, 'usercenter-fav-course.html', {
            'course_list': course_list,
            'MEDIA_URL': MEDIA_URL
        })
